<template>
	<canvas :id="canvasId" :canvas-id="canvasId" type="2d" class="lottie-canvas"></canvas>
</template>

<script>
	import lottie from 'lottie-miniprogram'
	export default {
		props: {
			width: {
				type: Number,
				value: 100
			},
			canvasId: {
				type: String,
				default: 'canvasId'
			},
			height: {
				type: Number,
				value: 100
			},
			path: {
				type: String,
				observer: function observer() {
					this.init();
				}
			}
		},
		onReady() {
			// 初始动画
			var that = this;
			that.init();
		},
		data() {
			return {
				show: true,
				_inited: false
			}
		},
		methods: {
			init() {
				if (this._inited) {
					return
				}
				this.createSelectorQuery().selectAll('#' + this.canvasId).node(res => {
					console.log(res)
					const canvas = res[0].node
					const context = canvas.getContext('2d')

					canvas.width = this.width
					canvas.height = this.height

					lottie.setup(canvas)
					this.lottie = lottie.loadAnimation({
						loop: true,
						autoplay: true,
						path: this.path,
						rendererSettings: {
							context,
						},
					})
					this._inited = true
				}).exec()
			},
			destory: function destory() {
				if (this.lottie) {
					this.lottie.destroy();
					this.lottie = null;
				}
			}
		},
		onUnload() {
			this.destory();
		}
	}
</script>

<style>
	.lottie-canvas {
		width: 100%;
		height: 100%;
	}
</style>
